class SmsVerification < ActiveRecord::Base
  before_create :set_random_code

  #向手机发送验证码
  def send_verification_code
    #md5pwd= "edde301ca9ff78134efbbaa6c2768bbf" #Digest::MD5.hexdigest('landong01')
    conv = Iconv.new("GBK","utf-8")
    s = "您的验证码是：【#{self.code}】。请不要把验证码泄露给其他人。" #"【东东租车】验证码#{self.code}"
    s1=conv.iconv(s)
    content = "account=cf_shunda&password=a123456&mobile=#{self.mobile}&content=#{s1}"
    response = RestClient.post "http://106.ihuyi.cn/webservice/sms.php?method=Submit", content
    #response.body == '100'
    # logger.info "response.status==#{response.code.to_s}"
    # logger.info "response.body==#{response.body}"
    nokogiri_document =  Nokogiri::XML(response.body)
    hash = Hash.from_xml(nokogiri_document.to_s)
    hash['SubmitResult']['code'].to_i==2
  end

  def not_expired?
    self.validated_at.nil?
  end

  def expire
    self.validated_at = Time.now
    self.save!
  end


  def excced_sms_peroid_limit?
    SmsVerification.where(mobile: self.mobile, created_at: (Time.now - 30.minutes)..Time.now).count > 5
  end

  def excced_sms_peroid_limit_json
    {error_code: 1, error_msg: '您的请求过于频繁，请稍后再试！'}.to_json
  end

  def excced_sms_day_limit?
    SmsVerification.where(mobile: self.mobile, created_at: (Time.now - 1.day)..Time.now).count > 15
  end

  def excced_sms_day_limit_json
    {error_code: 2, error_msg: '您1天内已达到最大请求数量，请次日再试！'}.to_json
  end

  def sms_send_failed_json
    {error_code: 0, error_msg: '短信发送失败，请联系管理员！'}.to_json
  end

protected
	def set_random_code
		self.code = newpass(6)
	end

  def newpass(len)
    newpass = ""
    1.upto(len){ |i| newpass << rand(10).to_s}
  	newpass
  end
end
